package com.sx.manage.controller.helps;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.sx.common.util.StringUtil;
import com.sx.common.util.json.JackJsonUtil;
import com.sx.manage.controller.base.MBaseController;
import com.sx.manage.service.helps.IMSysTemplateService;
import com.sx.manage.service.sys.IMBaseSystemConfigInfoService;
import com.sx.manage.servlet.ViewAndModel;
import com.sx.model.constants.MSystemConstants;
import com.sx.model.manage.mybatis.form.helps.MSysTemplateForm;
import com.sx.model.manage.mybatis.form.sys.MSystemConfigInfoForm;
import com.sx.model.manage.mybatis.vo.helps.MSysFileTemplateVO;
import com.sx.model.manage.mybatis.vo.result.ResultBooleanVO;
import com.sx.model.manage.mybatis.vo.result.ResultListVO;
import com.sx.model.manage.mybatis.vo.result.ResultObjectVO;
import com.sx.model.manage.mybatis.vo.result.ResultUploadVO;
import com.sx.model.manage.mybatis.vo.sys.MSysConfigVO;

/**
 * 模板管理
 * 
 * @author zwm
 *
 */
@Controller
@RequestMapping("/systemplate")
public class MSysTemplateController extends MBaseController {

	private Logger _log = LoggerFactory.getLogger(this.getClass());
	@Resource(name = "sysTemplateServiceImpl")
	private IMSysTemplateService mSysTemplateServiceImpl;
	@Resource(name = "mBaseSystemConfigInfoServiceImpl")
	private IMBaseSystemConfigInfoService mBaseSystemConfigInfoServiceImpl;

	public IMSysTemplateService getmSysTemplateServiceImpl() {
		return mSysTemplateServiceImpl;
	}

	public void setmSysTemplateServiceImpl(IMSysTemplateService mSysTemplateServiceImpl) {
		this.mSysTemplateServiceImpl = mSysTemplateServiceImpl;
	}

	public IMBaseSystemConfigInfoService getmBaseSystemConfigInfoServiceImpl() {
		return mBaseSystemConfigInfoServiceImpl;
	}

	public void setmBaseSystemConfigInfoServiceImpl(IMBaseSystemConfigInfoService mBaseSystemConfigInfoServiceImpl) {
		this.mBaseSystemConfigInfoServiceImpl = mBaseSystemConfigInfoServiceImpl;
	}

	/**
	 * 模板下载-添加模板
	 * 
	 * @return
	 */
	@RequestMapping(value = "template_index") // add_view_template
	public ViewAndModel add_view_sysFileTemplate() {
		ViewAndModel viewAndModel = new ViewAndModel(request, cache);
		// 如需在添加页需要加载元素在此处增加
		viewAndModel.setViewName("help/moduleDownload/addModule");// 淇敼ftl椤甸潰鍚嶇О
		viewAndModel.addObject("mSysFileTemplateVO", new MSysFileTemplateVO());
		return viewAndModel;
	}

	/**
	 * 模板下载-编辑模板
	 * 
	 * @param req
	 * @param resp
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	@RequestMapping(value = "template_eidt") // eidt_template
	@ResponseBody
	public ResultBooleanVO add_sysTemplateInfo(HttpServletRequest request, HttpServletResponse response) {
		if (null == request) {
			return new ResultBooleanVO("sj.m.common.add.error");
		}
		String request_message = extract_param_from_request(request);
		if (null == request_message || "".equals(request_message)) {
			return new ResultBooleanVO("sj.m.common.add.error");
		}
		MSysTemplateForm form = JackJsonUtil.jsonToJavaBean(request_message, MSysTemplateForm.class);
		if (null == form) {
			return new ResultBooleanVO("sj.m.common.add.error");
		}
		if (null != form.getId()) {
			return this.mSysTemplateServiceImpl.editSysTemplate(form, loginConsumer());
		} else {
			return this.mSysTemplateServiceImpl.addSysTemplate(form, loginConsumer());
		}
	}

	/**
	 * 模板下载-查询模板
	 * 
	 * @param form
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	@RequestMapping("/template_byid/{id}") // query_view_template
	@ResponseBody
	public ViewAndModel query_viewSysTemplate(MSysTemplateForm form) {
		ViewAndModel viewAndModel = new ViewAndModel(request, cache);
		ResultObjectVO<MSysFileTemplateVO> resultObjectVO = mSysTemplateServiceImpl.search_byId(form);
		MSysFileTemplateVO mSysFileTemplateVO = resultObjectVO.getObjVo();
		// 查询模板
		viewAndModel.setViewName("help/moduleDownload/addModule");
		viewAndModel.addObject("mSysFileTemplateVO", mSysFileTemplateVO);
		return viewAndModel;
	}

	/**
	 * 查询页面 进入
	 * 
	 * @return
	 */
	@RequestMapping("/template_view")
	public ViewAndModel search_viewSysTemplate() {
		ViewAndModel viewAndModel = new ViewAndModel(request, cache);
		// 如需在添加页需要加载元素在此处增加
		viewAndModel.setViewName("help/moduleDownload/moduleDownload");
		return viewAndModel;
	}

	/**
	 * 查询数据列表
	 * 
	 * @param form
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	@RequestMapping("/template_page")
	@ResponseBody
	public ResultListVO<MSysFileTemplateVO> search_sysTemplateInfo(MSysTemplateForm form) {
		ResultListVO<MSysFileTemplateVO> resultListVO = this.mSysTemplateServiceImpl.searchSysTemplateInfo(form);
		List<MSysFileTemplateVO> list = resultListVO.getData();
		if (!list.isEmpty()) {
			set_file_url(list);
		}
		return resultListVO;
	}

	/***
	 * [SysTemplateInfo]文件上传 流程
	 * 
	 * @param file
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/upload")
	@ResponseBody
	public ResultUploadVO<String> upload(@RequestParam(value = "files", required = false) MultipartFile file, HttpServletRequest request, ModelMap model) {
		String paths = null;
		String path = request.getSession().getServletContext().getRealPath("upload");
		String fileName = file.getOriginalFilename();
		File targetFile = new File(path, fileName);
		if (!targetFile.exists()) {
			targetFile.mkdirs();
		}
		try {
			file.transferTo(targetFile);
			// paths = OSSUtils.uploadFile(targetFile, MSystemConstants.SYS_UPLOAD_URL_);
			boolean flag = targetFile.delete();
			if (null == paths) {
				return new ResultUploadVO<>("sj.m.common.upload.error");
			}
			_log.info("上传文件成功，路径paths={},flag={} :", paths, flag);
		} catch (Exception e) {
			_log.error("文件上传异常error={}", e);
		}
		ResultUploadVO<String> result = new ResultUploadVO<>();
		result.setSuccess(true);
		result.setMsgcode("sj.m.common.upload.success");
		result.setPath(paths);
		return result;
	}

	/**
	 * 文件下载
	 * 
	 * @param filename
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@ResponseBody
	@RequestMapping(value = "/fileDownload/{pathName}/{filename}", produces = "application/json; charset=utf-8")
	public boolean wageDownload(@PathVariable String pathName, @PathVariable String filename, HttpServletRequest request, HttpServletResponse response) {
		_log.info("pathName:{}, filename:{}", pathName, filename);
		if (StringUtil.isBlank(filename) || StringUtil.isBlank(pathName)) {
			_log.info("文件下载失败，路径或文件名称为空");
			return false;
		}
		// String urlStr = OSSUtils.getFileUrl(filename, pathName);
//		_log.info("{}重定向路径为：{}", pathName, urlStr);
//		try {
//			response.sendRedirect(urlStr);
//		} catch (IOException e) {
//			_log.error("下载跳转重定向失败：{}", e);
//		}
		return true;
	}

	/**
	 * 增加下载路径处理
	 * 
	 * @param list
	 * @return
	 */
	public void set_file_url(List<MSysFileTemplateVO> list) {
		String template_url = template_url();
		for (MSysFileTemplateVO vo : list) {
			if (null != vo) {
				vo.setAccessory_address(template_url + vo.getAccessory_address());
			}
		}
	}

	public String template_url() {
		MSystemConfigInfoForm form = new MSystemConfigInfoForm();
		form.setConfig_name(MSystemConstants.TEMPLATE_DOWNLOAD_URL);
		MSysConfigVO configVO = mBaseSystemConfigInfoServiceImpl.queryByIdSystemConfig(form).getObjVo();
		if (null == configVO) {
			return null;
		}
		return configVO.getConfig_value();
	}

}
